package com.gxuwz.stats.service.excelhandler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.ResearchPlatform;
import com.gxuwz.stats.entity.ResearchProject;
import com.gxuwz.stats.entity.dto.ResearchProjectGxunDTO;
import com.gxuwz.stats.entity.dto.ResearchProjectHorizontalDTO;
import com.gxuwz.stats.service.SheetHandler;
import com.gxuwz.stats.service.SheetName;
import com.gxuwz.stats.service.excelNewHandler.ResearchProjectGxunListener;
import com.gxuwz.stats.service.excelNewHandler.ResearchProjectHorizontalListener;
import com.gxuwz.stats.service.impl.ResearchProjectServiceImpl;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@SheetName("科研项目工作量")
public class ResearchProjectHandler implements SheetHandler {
    @Autowired
    private ResearchProjectServiceImpl workloadService;

//    @Override
//    public void handle(Sheet sheet) {
//        // 将 Apache POI 的 Sheet 转换为 EasyExcel 的输入流（伪代码）
//        InputStream inputStream = convertSheetToInputStream(sheet);
//        String sheetName = sheet.getSheetName();
//        // 判断 sheetName 是否为空或为默认名（如 Sheet1），决定是否指定
//        if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
//            // 指定 sheet 名
//            EasyExcel.read(inputStream, ResearchProject.class, new ResearchProjectListener(workloadService))
//                    .sheet(sheetName)
//                    .headRowNumber(1)
//                    .doRead();
//        } else {
//            // 不指定 sheet 名，默认第一个
//            EasyExcel.read(inputStream, ResearchProject.class, new ResearchProjectListener(workloadService))
//                    .sheet()
//                    .headRowNumber(1)
//                    .doRead();
//        }
//        // 使用 EasyExcel 读取数据
////        EasyExcel.read(inputStream, ResearchProject.class, new ResearchProjectListener(workloadService))
////                .sheet("科研项目工作量")  // 指定 Sheet 名称
////                .doRead();
//    }

//    @Override
//    public List<String> getHeaderFields() {
//        // 这里写你的表头字段，和Excel第一行一致
//        return Arrays.asList("姓名", "项目名称", "类别", "项目级别", "项目状态", "经费（万）", "立项时间", "结题时间");
//    }

    private InputStream convertSheetToInputStream(Sheet sheet) {
        // 实现将 POI Sheet 转换为 InputStream 的逻辑（可能需要借助临时文件）
        // 此处仅为示例，实际需根据业务实现
        try {
            Workbook workbook = sheet.getWorkbook();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            workbook.write(out);
            return new ByteArrayInputStream(out.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("Sheet转换输入流失败", e);
        }
    }

//    @Override
public ImportResultProvider handle(Sheet sheet, String username, String role, String department) {
    org.apache.poi.ss.usermodel.Row headerRow = sheet.getRow(0);
    if (headerRow == null) {
        throw new RuntimeException("Excel表格缺少表头，无法识别模板类型！");
    }
    List<String> headers = new ArrayList<>();
    for (org.apache.poi.ss.usermodel.Cell cell : headerRow) {
        headers.add(cell.getStringCellValue().trim());
    }

    InputStream inputStream = convertSheetToInputStream(sheet);
    String sheetName = sheet.getSheetName();

    ImportResultProvider listener;

    // 原模板
    boolean isOriginal = headers.contains("姓名") && headers.contains("项目名称") && headers.contains("类别") && headers.contains("项目状态") && headers.contains("分值");
    // 广西高校科研项目
    boolean isGxun = headers.contains("录入人") && headers.contains("项目名称") && headers.contains("类型");
    // 广西高校横向项目
    boolean isHorizontal = headers.contains("录入人") && headers.contains("合同名称");

    if (isOriginal) {
        listener = new ResearchProjectListener(workloadService, username, role, department);
        if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
            EasyExcel.read(inputStream, ResearchProject.class, (AnalysisEventListener<ResearchProject>) listener)
                    .sheet(sheetName).headRowNumber(1).doRead();
        } else {
            EasyExcel.read(inputStream, ResearchProject.class, (AnalysisEventListener<ResearchProject>) listener)
                    .sheet().headRowNumber(1).doRead();
        }
    } else if (isGxun) {
        listener = new ResearchProjectGxunListener(workloadService, username, role, department);
        if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
            EasyExcel.read(inputStream, ResearchProjectGxunDTO.class, (AnalysisEventListener<ResearchProjectGxunDTO>) listener)
                    .sheet(sheetName).headRowNumber(1).doRead();
        } else {
            EasyExcel.read(inputStream, ResearchProjectGxunDTO.class, (AnalysisEventListener<ResearchProjectGxunDTO>) listener)
                    .sheet().headRowNumber(1).doRead();
        }
    } else if (isHorizontal) {
        listener = new ResearchProjectHorizontalListener(workloadService, username, role, department);
        if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
            EasyExcel.read(inputStream, ResearchProjectHorizontalDTO.class, (AnalysisEventListener<ResearchProjectHorizontalDTO>) listener)
                    .sheet(sheetName).headRowNumber(1).doRead();
        } else {
            EasyExcel.read(inputStream, ResearchProjectHorizontalDTO.class, (AnalysisEventListener<ResearchProjectHorizontalDTO>) listener)
                    .sheet().headRowNumber(1).doRead();
        }
    } else {
        throw new RuntimeException("无法识别的科研项目导入模板，请检查表头！");
    }
    return listener;
}
}
